package test1.authenticator;


import java.util.Collection;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.pam.AbstractAuthenticationStrategy;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.util.CollectionUtils;

/**
 * 至少有两条验证规则
 */
public class AtLeastTwoSuccessfulStrategy extends AbstractAuthenticationStrategy{

	/**
	 * 返回权限认证信息
	 */
	public AuthenticationInfo beforeAllAttempts(Collection<? extends Realm> realms,AuthenticationToken token)throws AuthenticationException{
		
		return new SimpleAuthenticationInfo();
	}
	
	/**
	 * 返回之前合并的信息
	 */
	public AuthenticationInfo beforeAttempt(Realm realm,AuthenticationToken token,AuthenticationInfo aggregate)throws AuthenticationException{
		
		
		return aggregate;
	}
	
	/**
	 * 返回权限认证信息,传递权限认证信息
	 */
	public AuthenticationInfo afterAttempt(Realm realm,AuthenticationToken token,AuthenticationInfo singleRealmInfo,AuthenticationInfo aggregate,Throwable t)throws AuthenticationException{
		AuthenticationInfo info= null;
		if(null==singleRealmInfo){
			info= aggregate;
		}else{
			if(null==aggregate){
				info= singleRealmInfo;
			}else{
				info= merge(singleRealmInfo,aggregate);
			}
		}
		return info;
	}
	
	/**
	 * 返回权限验证信息,进行认证
	 */
	public AuthenticationInfo afterAllAttempts(AuthenticationToken token,AuthenticationInfo aggregate)throws AuthenticationException{
		if(null==aggregate || CollectionUtils.isEmpty(aggregate.getPrincipals()) || aggregate.getPrincipals().getRealmNames().size()<2){
			throw new AuthenticationException("Authentication token of type [" + token.getClass() + "] " +
                    "could not be authenticated by any configured realms.  Please ensure that at least two realm can " +
                    "authenticate these tokens.");			
		}
		
		return aggregate;
	}
}
